<template>
  <div class="search-form">
    <!-- 头部tab切换 -->
    <el-row type="flex" class="search-tab">
      <span
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleSearchTab(item, index)"
        :class="{active: index === currentTab}"
      >
        <i :class="item.icon"></i>
        {{item.name}}
      </span>
    </el-row>

    <el-form class="search-form-content" ref="form" label-width="80px">
      <el-form-item label="出发城市">
        <!-- fetch-suggestions 返回输入建议的方法 -->
        <!-- select 点击选中建议项时触发 -->
        <el-autocomplete
          :fetch-suggestions="queryDepartSearch"
          placeholder="请搜索出发城市"
          @select="handleDepartSelect"
          class="el-autocomplete"
          v-model="form.departCity"
          @blur="handleDepartBlur"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="到达城市">
        <el-autocomplete
          :fetch-suggestions="queryDestSearch"
          placeholder="请搜索到达城市"
          @select="handleDestSelect"
          class="el-autocomplete"
          v-model="form.destCity"
          @blur="handleDestBlur"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="出发时间">
        <!-- change 用户确认选择日期时触发 -->
        <el-date-picker
          type="date"
          placeholder="请选择日期"
          style="width: 100%;"
          @change="handleDate"
          v-model="form.departDate"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label>
        <el-button style="width:100%;" type="primary" icon="el-icon-search" @click="handleSubmit">搜索</el-button>
      </el-form-item>
      <div class="reverse">
        <span @click="handleReverse">换</span>
      </div>
    </el-form>
  </div>
</template>

<script>
// 引入momentjs
import moment from "moment";
export default {
  data() {
    return {
      form: {
        departCity: "", //出发城市
        departCode: "", //出发城市代码
        destCity: "", //目的地
        destCode: "",
        departDate: "" //日期字符串
      },
      tabs: [
        { icon: "iconfont icondancheng", name: "单程" },
        { icon: "iconfont iconshuangxiang", name: "往返" }
      ],
      currentTab: 0,
      // 出发城市列表 存放第一项建议城市
      departCityArr: [],
      destCityArr: [],
      // 选择日期
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        }
      }
    };
  },
  methods: {
    // tab切换时触发
    handleSearchTab(item, index) {
      // this.currentTab = index;
      if (index === 1) {
        this.$alert("暂不支持往返车票", "提示", { type: "warning" });
      }
    },

    // 出发城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    queryDepartSearch(value, cb) {
      // 获取出发城市
      // 我们发现当输入框没有数据时，也会触发下拉框所以当没有数据 我们返回一个空列表
      if (!value.trim()) return cb([]);
      this.$axios({
        url: "/airs/city",
        // 带上api文档中写的参数
        params: {
          name: value
        }
      }).then(res => {
        const { data } = res.data;
        // 由于我们拿到的数据中后面都带市字，而我们请求搜索的时候url上不带，所以遍历数组去掉市字
        // 最后返回新数组 我们用map方法循环数组 v表示每一项数据
        this.departCityArr = data.map(v => {
          // 添加一个value
          v.value = v.name.replace("市", "");
          return v;
        });
        // console.log(newData);
        // 调用callback函数返回建议列表数据
        cb(this.departCityArr);
      });
    },
    // 目标城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    queryDestSearch(value, cb) {
      if (!value.trim()) return cb([]);
      this.$axios({
        url: "/airs/city",
        // 带上api文档中写的参数
        params: {
          name: value
        }
      }).then(res => {
        const { data } = res.data;
        this.destCityArr = data.map(v => {
          v.value = v.name.replace("市", "");
          return v;
        });
        cb(this.destCityArr);
        // console.log(this.destCityArr);
      });
    },

    // 出发城市下拉选择时触发
    handleDepartSelect(item) {
      // console.log(item);
      // 根据选择获取该城市的数据 赋值给对应的data数据
      this.form.departCity = item.value;
      this.form.departCode = item.sort;
    },

    // 目标城市下拉选择时触发
    handleDestSelect(item) {
      this.form.destCity = item.value;
      this.form.destCode = item.sort;
    },
    // 失去焦点触发默认选择第一项
    handleDepartBlur() {
      // 如果我们直接在输入框输入地点后没有选择下拉建议框， 是获取不到城市代码的 所以我们要在用户输入失去焦点让她默认选中第一项数据
      // 创建departCity 和departCode 并将建议列表第一项值给departCityArr
      // 如果输入框没有数据 不执行
      if (this.departCityArr.length === 0) return;
      this.form.departCity = this.departCityArr[0].value;
      this.form.departCode = this.departCityArr[0].sort;
    },
    handleDestBlur() {
      if (this.destCityArr.length === 0) return;
      console.log(this.destCityArr);
      this.form.destCity = this.destCityArr[0].value;
      this.form.destCode = this.destCityArr[0].sort;
    },
    // 确认选择日期时触发
    handleDate(value) {
      // console.log(this.form);
      // 输出发现我们拿到的数据是：departDate: Wed Nov 13 2019 00:00:00 GMT+0800 (中国标准时间) 我们要转换YYYY-MM-DD 用
      // 我们使用了momentjs，这是一个第三方的包 转换日期
      this.form.departDate = moment(value).format("YYYY-MM-DD");
    },

    // 触发和目标城市切换时触发
    handleReverse() {
      const { departCity, departCode, destCity, destCode } = this.form;
      this.form.departCity = destCity;
      this.form.departCode = destCode;
      this.form.destCity = departCity;
      this.form.destCode = departCode;
    },

    // 提交表单是触发
    handleSubmit() {
      // 提交跳转到机票列表
      // 发送ajax请求;
      // console.log(this.form);
      // 判断 表单项不能为空 否则弹框提醒不跳转 定义一个数组
      const rules = [
        { value: this.form.departCity, message: "请输入出发城市" },
        { value: this.form.destCity, message: "请输入目的城市" },
        { value: this.form.departDate, message: "请输入出发日期" }
      ];
      // 遍历数组判断不能为空
      let valid = true;
      rules.forEach(e => {
        if (!valid) return;
        if (!e.value) {
          this.$alert(e.message, "提示", { type: "warning" });
          valid = false;
        }
      });
      // 只要有一个为空 就不跳转
      if (!valid) return;

      // 保存到vuex的store中
      this.$store.commit("air/setHistory",this.form);
      // 路由跳转 跳转到机票详情 带上参数
      this.$router.push({
        path: "/air/flights",
        // 参数在url后用query
        query: this.form
      });
    }
  },
  mounted() {}
};
</script>

<style scoped lang="less">
.search-form {
  border: 1px #ddd solid;
  border-top: none;
  width: 360px;
  height: 350px;
  box-sizing: border-box;
}

.search-tab {
  span {
    display: block;
    flex: 1;
    text-align: center;
    height: 48px;
    line-height: 42px;
    box-sizing: border-box;
    border-top: 3px #eee solid;
    background: #eee;
  }

  .active {
    border-top-color: orange;
    background: #fff;
  }

  i {
    margin-right: 5px;
    font-size: 18px;

    &:first-child {
      font-size: 16px;
    }
  }
}

.search-form-content {
  padding: 15px 50px 15px 15px;
  position: relative;

  .el-autocomplete {
    width: 100%;
  }
}

.reverse {
  position: absolute;
  top: 35px;
  right: 15px;

  &:after,
  &:before {
    display: block;
    content: "";
    position: absolute;
    left: -35px;
    width: 25px;
    height: 1px;
    background: #ccc;
  }

  &:after {
    top: 0;
  }

  &:before {
    top: 60px;
  }

  span {
    display: block;
    position: absolute;
    top: 20px;
    right: 0;
    font-size: 12px;
    background: #999;
    color: #fff;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;

    &:after,
    &:before {
      display: block;
      content: "";
      position: absolute;
      left: 10px;
      width: 1px;
      height: 20px;
      background: #ccc;
    }

    &:after {
      top: -20px;
    }

    &:before {
      top: 20px;
    }
  }
}
</style>
